package com.mylogistics.common.Utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JWTUtil {
    //定义密钥
    public static final String SECRET ="zdasdas";
    //设置过期时间
    public static final long EXPRIED = 1000*60*3;
    //设置最终过期时间
    public static final long FRESH = 1000*60*10;
    //定义用户账号
    public static final String ACCOUNT = "account";
    //存储token值
    public static Map<String, Long> createTimes = new HashMap<>();

    //实现jwt的token的创建
    public static String create(String account){
        //根据密码创建算法，secret是密钥，可以自定义
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        String token = JWT.create()
                .withClaim(ACCOUNT,account)
                .withExpiresAt(new Date(System.currentTimeMillis()+EXPRIED))
                .sign(algorithm);
        createTimes.put(token,System.currentTimeMillis());
        return token;
    }
    //失效后新token的创建
    public static String create(String account,String oldToken){
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        String token = JWT.create()
                .withClaim(ACCOUNT,account)
                .withExpiresAt(new Date(System.currentTimeMillis()+EXPRIED))
                .sign(algorithm);
        createTimes.put(token,System.currentTimeMillis());
        createTimes.remove(oldToken);
        return token;
    }
    //实现jwt的验证
    public static boolean verify(String token){
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                    .build(); //Reusable verifier instance
            DecodedJWT jwt = verifier.verify(token);
            log.info("verify jwt success");
            return true;
        } catch (JWTVerificationException exception){
            throw exception;
        }
    }
    //根据token获取用户名
    public static String getAccount(String token){
        DecodedJWT jwt = JWT.decode(token);
        //获取自定义参数,获取之前用户的名称
        String account =  jwt.getClaim(ACCOUNT).asString();
        return account;
    }

    //判断token是否能以旧换新
    public static Boolean getCreateTime(String token){
        Long time = createTimes.get(token);
        Long newTime = System.currentTimeMillis();
        if(time==null)return false;
        if(newTime-time>FRESH){
            return false;
        }else return true;
    }

    //判断token是否存在
    public static Boolean isEmpty(String token){
        return createTimes.get(token)==null;
    }
}
